package com.aw.guiguzi.module.manager.transaction

import android.os.Handler
import android.view.View
import com.aw.baselib.base.AwMvpBindingActivity
import com.aw.baselib.bean.CommonImgItemBean
import com.aw.baselib.interfaces.IPermissionListener
import com.aw.baselib.util.AwDataUtil
import com.aw.baselib.util.AwFileUtil
import com.aw.baselib.util.AwGsonUtil
import com.aw.baselib.util.AwLog
import com.aw.baselib.util.AwRecyclerViewUtil
import com.aw.baselib.util.AwRxPermissionUtil
import com.aw.baselib.util.pictureutil.PictureUtils
import com.aw.guiguzi.R
import com.aw.guiguzi.base.MyApp
import com.aw.guiguzi.bean.TransactionItemBean
import com.aw.guiguzi.constants.MyConstant
import com.aw.guiguzi.databinding.ActivityManagerTransactionConfigBinding
import com.aw.guiguzi.event.EventRefreshTransactionListType
import com.aw.guiguzi.event.EventRefreshUserInfoType
import com.aw.guiguzi.module.manager.transaction.adapter.ManagerTransactionConfigAdapter
import com.aw.guiguzi.module.manager.transaction.adapter.ManagerTransactionConfigSubItemAdapter
import com.aw.guiguzi.module.manager.transaction.presenters.ManagerTransactionConfigPresent
import com.aw.guiguzi.module.manager.transaction.views.ManagerTransactionConfigView
import com.aw.guiguzi.util.AppUserUtil.user
import com.aw.guiguzi.util.DataUtil.defaultTransactionList
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.gson.reflect.TypeToken
import com.luck.picture.lib.entity.LocalMedia

class ManagerTransactionConfigActivity :
    AwMvpBindingActivity<ManagerTransactionConfigPresent?, ActivityManagerTransactionConfigBinding?>(),
    ManagerTransactionConfigView.View {
    private var mlist: MutableList<TransactionItemBean> = ArrayList()
    private var mAdapter: ManagerTransactionConfigAdapter? = null
    private var mSubAdapter: ManagerTransactionConfigSubItemAdapter? = null
    override fun getViewBinding(): ActivityManagerTransactionConfigBinding {
        return ActivityManagerTransactionConfigBinding.inflate(
            layoutInflater
        )
    }

    override fun initView() {
        super.initView()
        setToolbarWithBackImgAndRightView("配置", "保存") {
            for (i in mlist.indices) {
                val itemBean = mlist[i]
                AwLog.d("保存数据TransactionItemBean: $itemBean")
            }
            val remark = AwGsonUtil.toJson(mlist)
            //1, 写入文件, 2, 上传文件 3, 拿到地址 4,更新用户信息备注
            val filePath =
                AwFileUtil.writeFile(mActivity, MyConstant.DEFAULT_TRANSACTION_TXT, remark)
            mPresenter!!.uploadFile(filePath)
        }
    }

    override fun initData() {
        super.initData()
        //        mlist = DataUtil.getDefaultTransactionList();
        mlist = if (AwDataUtil.isEmpty(MyApp.transactionData)) {
            defaultTransactionList as MutableList<TransactionItemBean>
        } else {
            AwGsonUtil.fromJson(
                MyApp.transactionData,
                object : TypeToken<List<TransactionItemBean?>?>() {}.type
            )
        }
        mAdapter = ManagerTransactionConfigAdapter()
        AwRecyclerViewUtil.setRecyclerViewLinearlayout(
            mActivity,
            binding!!.rcvData,
            mAdapter,
            false
        )
        mAdapter!!.addAllData(mlist)
        mAdapter!!.setOnItemChildClickListener { adapter: BaseQuickAdapter<*, *>, view: View, position: Int ->
            if (view.id == R.id.tv_add) {
                val itemBean = adapter.getItem(position) as TransactionItemBean?
                if (itemBean!!.list.size == 0) {
                    itemBean.list.add(CommonImgItemBean("", ""))
                    mAdapter!!.notifyDataSetChanged()
                } else if (itemBean!!.list.size < 6) {
                    if (AwDataUtil.isEmpty(itemBean.list[itemBean.list.size - 1].describe) || AwDataUtil.isEmpty(
                            itemBean.list[itemBean.list.size - 1].imgPath
                        )
                    ) {
                        showMsg("请先完善最后一条")
                        return@setOnItemChildClickListener
                    }
                    itemBean.list.add(CommonImgItemBean("", ""))
                    mAdapter!!.notifyDataSetChanged()
                } else {
                    showMsg("已达到可增加最大数量")
                }
            } else if (view.id == R.id.iv_delCategorize) {
                showDialogWithCancelDismiss("确定要删除该分类吗？") { v: View? ->
                    mlist.removeAt(position)
                    mAdapter!!.addAllData(mlist)
                }
            }
        }
        mAdapter!!.setUploadListener(object : ManagerTransactionConfigAdapter.OnUploadListener {
            override fun toUpload(
                bean: CommonImgItemBean?,
                subAdapter: ManagerTransactionConfigSubItemAdapter?
            ) {
                for (i in mlist.indices) {
                    val itemBean = mlist[i]
                    AwLog.d("选图前: $itemBean")
                }

                mSubAdapter = subAdapter
                AwRxPermissionUtil.getInstance().checkPermissions(
                    mActivity,
                    AwRxPermissionUtil.getStoragePermissions(),
                    object : IPermissionListener {
                        override fun granted() {
                            AwLog.d("checkPermissions file granted...")
                            val selectResult = ArrayList<LocalMedia>()
                            PictureUtils.createImageMax(mActivity, 1, selectResult) { list ->
                                if (list != null && list.size > 0) {
                                    for (i in mlist.indices) {
                                        val itemBean = mlist[i]
                                        AwLog.d("选图后: $itemBean")
                                    }
                                    AwLog.d("createImageMax getRealPath: " + list[0].realPath)
                                    AwLog.d("createImageMax getCutPath: " + list[0].cutPath)
                                    AwLog.d("createImageMax getCompressPath: " + list[0].compressPath)
                                    mPresenter!!.uploadFile(bean, list[0].cutPath)
                                } else {
                                    showMsg("图片地址获取失败")
                                }
                            }
                        }

                        override fun shouldShowRequestPermissionRationale() {
                            AwLog.d("checkPermissions file shouldShowRequestPermissionRationale...")
                            showMsg("请到设置中开启权限")
                        }

                        override fun needToSetting() {
                            AwLog.d("checkPermissions file needToSetting...")
                            showMsg("请到设置中开启权限")
                        }
                    })
            }
        })
    }

    override fun initListener() {
        super.initListener()
        binding?.tvAdd?.setOnClickListener{view : View ->
            if(mlist?.size!! < 6) {
                var list: MutableList<CommonImgItemBean> = ArrayList()
                mlist.add(TransactionItemBean("新增类别", list))
                mAdapter?.notifyDataSetChanged()
                binding?.rcvData?.scrollToPosition(mlist.size - 1)
            } else {
                showMsg("已达最大类别数量")
            }

        }
    }

    override fun createPresenter(): ManagerTransactionConfigPresent {
        return ManagerTransactionConfigPresent(this)
    }

    override fun uploadFileSuccess(result: String?) {
        val userInfoBean = user
        userInfoBean!!.remark = result
        mPresenter!!.updateUserRemark(userInfoBean)
    }

    override fun uploadFileSuccess(bean: CommonImgItemBean?, result: String?) {
        showMsg("上传成功")
        bean!!.imgPath = result
        for (i in mlist.indices) {
            val itemBean = mlist[i]
            AwLog.d("上传后: $itemBean")
        }
//        mAdapter!!.addAllData(mlist)
        //TODO 上传后直接修改提交, 不做本地刷新展示 ( 有些问题, 刷新后类别名称错乱 )
        val remark = AwGsonUtil.toJson(mlist)
        //1, 写入文件, 2, 上传文件 3, 拿到地址 4,更新用户信息备注
        val filePath =
            AwFileUtil.writeFile(mActivity, MyConstant.DEFAULT_TRANSACTION_TXT, remark)
        mPresenter!!.uploadFile(filePath)
    }

    override fun updateUserRemarkSuccess() {
        postEvent(EventRefreshTransactionListType(mlist))
        postEvent(EventRefreshUserInfoType(null))
        finish()
    }
}